/*
 *Copyright © 2015 zhaorongbao
 *招融宝
 *http://zhaorongbao.com
 *All rights reserved.
 */
package com.hanhai.zrb.api.biz.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.hanhai.zrb.api.biz.dao.mybatis.CheckcodeTemplateDao;
import com.hanhai.zrb.api.biz.service.CheckcodeTemplateService;
import com.hanhai.zrb.model.common.CheckcodeTemplate;
import com.hanhai.zrb.model.common.ValidateCodeSend.BizTypeEnum;

@Service
public class CheckcodeTemplateServiceImpl implements CheckcodeTemplateService {

	@Resource
	private CheckcodeTemplateDao checkcodeTemplateDao;
	
	private Logger logger = Logger.getLogger(getClass());
	
	private static List<CheckcodeTemplate>  checkcodeTemplateList;
	@Override
	public List<CheckcodeTemplate> list() {
		if(checkcodeTemplateList==null){
			refreshCheckcodeTemplate();
		}
		return checkcodeTemplateList;
	}
	
	@Scheduled(cron = "0 0/10 * * * ? ")
	// 每10分钟一次
	public void refreshCheckcodeTemplate() {
		checkcodeTemplateList = checkcodeTemplateDao.list();
		logger.info("refreshCheckcodeTemplate,size="+checkcodeTemplateList.size());
	}
	
	public CheckcodeTemplate findCheckcodeTemplate(String configName){
		List<CheckcodeTemplate> checkcodeTemplateList=list();
		CheckcodeTemplate contentTemplate = findCheckcodeTemplate(configName,checkcodeTemplateList);
		return contentTemplate;
	}
	
	private CheckcodeTemplate findCheckcodeTemplate(String configName,
			List<CheckcodeTemplate> checkcodeTemplateList) {
		CheckcodeTemplate  defaultTemplate = new CheckcodeTemplate();
		defaultTemplate.setContent(BizTypeEnum.Default.getContent());
		defaultTemplate.setSubject(BizTypeEnum.Default.getSubject());
		if(checkcodeTemplateList == null){	
			logger.error("Cannot find sms-mail template,name="+configName);
			return defaultTemplate;
		}
		for(CheckcodeTemplate template:checkcodeTemplateList){
			if(template.getName().equals(configName)){
				return template;
			}
		}
		logger.error("Cannot find sms-mail template,name="+configName);
		return defaultTemplate;
	}

}
